package com.shijie.component;

import com.shijie.component.redis.RedisClient;
import com.shijie.component.redis.RedisKey;
import com.shijie.core.constants.PnConstant;
import com.shijie.domain.vo.BaseUserVo;
import com.shijie.mapper.UsersMapper;
import com.shijie.utils.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * Created with Yang Huan
 * Date: 2017/3/2
 * Time: 11:34
 */
@Component
@Aspect
public class AppUserService {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private UsersMapper usersMapper;

    public Boolean isLogin() {
        return null != getCurrentUser();
    }

    public String createUserToken(BaseUserVo user) {
        String token = String.format(PnConstant.CACHE_TOKEN_KEY, "app", UUID.randomUUID().toString());
        redisClient.put(String.format(RedisKey.APP_USER_CACHE, token), user, 3600l);
        return token;
    }

    public String getUserName() {
        BaseUserVo user = this.getCurrentUser();
        if (user == null) return null;
        return user.getTrueName() == null ? user.getNickName() : user.getTrueName();
    }

    public BaseUserVo getCurrentUser() {
        // 基本信息 用户点赞数，建议取数据库信息
        String userToken = CommonUtil.getRequest().getParameter(String.format(PnConstant.PARAMETER_TOKEN_KEY, "app"));
        if (StringUtils.isNotBlank(userToken)) {
            BaseUserVo user = (BaseUserVo) redisClient.get(String.format(RedisKey.APP_USER_CACHE, userToken));
            if (null != user) {
                redisClient.put(String.format(RedisKey.APP_USER_CACHE, userToken), user, 3600l);
                return user;
            }
        }
        return null;
        //return new BaseUserVo(usersMapper.selectByPrimaryKey(100000084));
    }
}
